package com.touringapp.android.utils.http;

import java.io.IOException;
import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import com.touringapp.android.utils.IOUtils;
import com.touringapp.android.utils.Logger;
import com.touringapp.android.utils.ResponseStatus;
import com.touringapp.android.utils.constants.Constants;

import android.util.Log;

public class RequestUtility {
    static final int LOGGER_ENTRY_MAX_LEN = 4000;
	public static JSONObject executePostRequest(final String requestUrl,
			final JSONObject json) throws HttpException, JSONException, IOException, UnexpectedServerException, HttpErrorCodeException {
		HashMap<String, Object> params = new HashMap<String, Object>();
		params.put("post", json.toString());

		return handleResponse(HttpUtil.executePost(requestUrl, params));

	}

	public static JSONObject handleResponse(
			HttpResponse response) throws JSONException, IOException, UnexpectedServerException, HttpErrorCodeException {
		final int httpStatusCode = response.getStatusCode();
		if (httpStatusCode == 200) {

			JSONObject responseJSON = response.getJSONResult();
			if (response.getJSONResult() == null) {
				final String responseData = IOUtils.toString(response
						.getResponseStream());
	
					responseJSON = new JSONObject(responseData);
					logResponse(response, responseData);
			}

			ResponseStatus responseStatus = null;
			responseStatus = ResponseStatus.fromJSONObject(responseJSON
					.getJSONObject("status"));

			int resultCode = responseStatus.getResultCode();
			if (0 == resultCode) {
				return responseJSON;
			} else {
				throw new UnexpectedServerException();
			}

		} else {
			// String responseData =
			// IOUtils.toString(response.getResponseStream());
			throw new HttpErrorCodeException(httpStatusCode,
					"HTTP request failed with status-code"
							+ response.getStatusCode());
		}
	}
	
    protected static void logResponse(HttpResponse response, final String responseData) {
        if (!Log.isLoggable(Constants.LOG_TAG_RESPONSE, Log.VERBOSE))
            return;
        Log.v(Constants.LOG_TAG_RESPONSE, Logger.buildString(" ",Constants.LOG_TAG_RESPONSE, 
                "Request repsonse. request url:", response.getRequestUrl()));
        final int lines = (responseData.length() + LOGGER_ENTRY_MAX_LEN - 1) / LOGGER_ENTRY_MAX_LEN;
        int pos = -LOGGER_ENTRY_MAX_LEN;
        for (int i = 0; i < lines; i++) {
            pos += LOGGER_ENTRY_MAX_LEN;
            int end = pos + LOGGER_ENTRY_MAX_LEN;
            if (end >= responseData.length())
                end = responseData.length() - 1;
            Log.v(Constants.LOG_TAG_RESPONSE, Logger.buildString(" ", 
                    Constants.LOG_TAG_RESPONSE,
                    responseData.substring(pos, end)));
        }
    }


}
